

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  <title>浏览器渲染以及性能优化 - Hexo</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_pf9vaxs7x7b.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>Zchaos</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/post.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-10-07 23:20" pubdate>
        2020年10月7日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.4k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      14
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">浏览器渲染以及性能优化</h1>
            
            <div class="markdown-body" id="post-body">
              <h1 id="浏览器渲染以及性能优化"><a href="#浏览器渲染以及性能优化" class="headerlink" title="浏览器渲染以及性能优化"></a>浏览器渲染以及性能优化</h1><h2 id="浏览器渲染大致流程"><a href="#浏览器渲染大致流程" class="headerlink" title="浏览器渲染大致流程"></a>浏览器渲染大致流程</h2><h3 id="DOM树构建"><a href="#DOM树构建" class="headerlink" title="DOM树构建"></a>DOM树构建</h3><ul>
<li>根据HTML文档的内容，根据标签进行分词Token</li>
<li>根据Token生产对应的节点Node</li>
<li>将节点根据嵌套关系组合为一棵对象节点树DOM</li>
</ul>
<blockquote>
<p>浏览器解析文档对象模型DOM是增量进行的,无需等待整个HTML文档加载完毕，便可以开始解析DOM.CSSOM解析和JavaScript脚本文件执行会阻塞HTML Parser</p>
</blockquote>
<h3 id="CSSOM树的构建"><a href="#CSSOM树的构建" class="headerlink" title="CSSOM树的构建"></a>CSSOM树的构建</h3><p>CSSOM的解析依赖于选择器，选择器的匹配是从内到外的。所以选择器嵌套层次越深，匹配的时间会越长。</p>
<blockquote>
<p>CSSOM只解析可视部分body标签中的内容，将所有匹配的元素共同构建一个CSSOM树，从根节点一次向下，所有节点的属性向下继承</p>
</blockquote>
<h3 id="RenderTree树的构建"><a href="#RenderTree树的构建" class="headerlink" title="RenderTree树的构建"></a>RenderTree树的构建</h3><p>利用DOM和CSSOM组合构建生成RenderTree，对应Recaculate Style</p>
<blockquote>
<p>RenderTree中包含所有渲染网页必须的节点<br>无需渲染的节点不会被添加到RenderTree中，如head和display:none;的节点<br>visibility: hidden;的节点会添加到RenderTree中</p>
</blockquote>
<h3 id="Layout"><a href="#Layout" class="headerlink" title="Layout"></a>Layout</h3><p>Layout利用渲染树的信息，计算渲染树中所有节点在页面上的位置和大小。</p>
<blockquote>
<p>类似绘画中各个元素位置摆放及尺寸规划</p>
</blockquote>
<p>会引起页面重新Layout的操作：所有改变节点位置和大小的操作</p>
<ul>
<li>屏幕旋转</li>
<li>浏览器视窗改变</li>
<li>与大小、位置相关的CSS属性</li>
<li>增加与删除DOM元素</li>
</ul>
<blockquote>
<p>Layout操作比较耗时，对于动画中频繁引起Layout的操作（元素位置移动），最好使用transform代替，可以使用GPU进行动画处理（将Layout重绘在GPU完成）</p>
</blockquote>
<h3 id="Paint"><a href="#Paint" class="headerlink" title="Paint"></a>Paint</h3><p>填充Layout中的具体内容和样式，将Layout生成的区域填充为最终显示在屏幕上的像素</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ol>
<li>浏览器通过GET请求获取网页HTML，同时将增量解析HTML文档，生成DOM树</li>
<li>解析DOM节点树时，对于需要加载的资源全部执行异步加载，但是CSS的解析、JavaScript的执行与font文件的下载会阻塞HTML Parser</li>
<li>局部DOM树与CSSOM树构建完成后，立即组装RenderTree进行渲染</li>
</ol>
<h2 id="性能优化"><a href="#性能优化" class="headerlink" title="性能优化"></a>性能优化</h2><h3 id="css文件"><a href="#css文件" class="headerlink" title="css文件"></a>css文件</h3><blockquote>
<p>css加载会阻塞初次渲染.浏览器在解析完css后，再进行渲染。防止样式突变带来的抖动。</p>
</blockquote>
<p><strong>优化方式</strong></p>
<ul>
<li>使用media=print媒体查询，虽然加载样式表，但只针对打印时才应用该样式，不会阻塞初次渲染。(只有匹配的时候才会阻塞)</li>
<li>通过DOMAPI引入CSS，可以避免阻塞.</li>
<li><link rel="preload" href="index_print.css" as="style" onload="this.rel='stylesheet'">注意preload的兼容性不是很好</li>
<li>对使用多个外链的网页请使用<link rel="dns-prefetch" href="http://www.spreadfirefox.com/">强制开启DNS 预读取，能够减少用户点击链接时的延迟。</li>
</ul>
<h3 id="JS文件"><a href="#JS文件" class="headerlink" title="JS文件"></a>JS文件</h3><blockquote>
<p>JS脚本执行会阻塞HTML Parser；<br>CSS解析会阻塞JS脚本执行：js可能会读、写CSSOM<br>虽然JS会阻塞HTML Parser解析；但是浏览器的资源异步加载机制Preload会异步加载head标签内的资源</p>
</blockquote>
<ul>
<li>使用&lt;script&gt;的defer属性和async属性，defer属性适用于需要严格按照HTML文档中出现的顺序执行js文件，async属性适用于适用于无依赖的外部独立资源。</li>
</ul>
<h3 id="优化关键渲染路径"><a href="#优化关键渲染路径" class="headerlink" title="优化关键渲染路径"></a>优化关键渲染路径</h3><ul>
<li>关键资源数—初次渲染时依赖的资源(内联资源(内联共享资源,建议采用缓存机制))</li>
<li>关键资源的体积最小—压缩文件或图片</li>
<li>关键资源网络来回数—网络传输资源消耗很多时间</li>
</ul>
<h3 id="减少reflow-repaint"><a href="#减少reflow-repaint" class="headerlink" title="减少reflow/repaint"></a>减少reflow/repaint</h3><blockquote>
<p>Repaint表示屏幕的一部分要重画，比如某个CSS的背景色变了。但是元素的几何尺寸没有变。<br>Reflow意味着元件的几何尺寸变了，我们需要重新验证并计算Render Tree。</p>
</blockquote>
<p><strong>触发场景：</strong></p>
<ul>
<li>当你增加、删除、修改DOM结点时，会导致Reflow或Repaint</li>
<li>当你移动DOM的位置，或是搞个动画的时候。</li>
<li>当你修改CSS样式的时候。</li>
<li>当你Resize窗口的时候（移动端没有这个问题），或是滚动的时候。</li>
<li>当你修改网页的默认字体时。</li>
<li>width, clientWidth, scrollTop等布局宽高的计算</li>
</ul>
<p><strong>优化方式</strong></p>
<ol>
<li>不要一条一条地修改DOM的样式。与其这样，还不如预先定义好css的class，然后修改DOM的className。</li>
<li>把DOM离线后修改。(利用documentFragment 对象)</li>
<li>不要把DOM结点的属性值放在一个循环里当成循环里的变量。</li>
<li>尽可能的修改层级比较低的DOM。当然，改变层级比较底的DOM有可能会造成大面积的reflow，但是也可能影响范围很小。</li>
<li>为动画的HTML元件使用fixed或absoult的position，那么修改他们的CSS是不会reflow的</li>
<li>千万不要使用table布局。因为可能很小的一个小改动会造成整个table的重新布局。</li>
</ol>
<h2 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h2><p>什么是白屏和FOUC(无样式内容闪烁)?</p>
<blockquote>
<p>不同的浏览器对于CSS和HTML的处理方式不同，有的是等待CSS加载完成之后，对HTML元素进行渲染和展示(白屏问题)。有的是先对HTML元素进行展示，然后等待CSS加载完成之后重新对样式进行修改(FOUC无样式内容闪烁)</p>
</blockquote>
<p><strong>参考：</strong></p>
<p><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000008693178?share_user=1030000008431166&utm_source=Weibo&utm_medium=shareLink&utm_campaign=socialShare#articleHeader4">Web性能优化</a><br><a target="_blank" rel="noopener" href="http://coolshell.cn/articles/9666.html">浏览器渲染解析</a><br><a target="_blank" rel="noopener" href="http://coolshell.cn/articles/9749.html">JAVASCRIPT 装载和执行</a><br><a target="_blank" rel="noopener" href="https://www.chengrang.com/how-browsers-work.html">浏览器工作原理分析与首屏加载</a></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">性能优化</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">性能优化</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/10/09/URL/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">URL</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/10/07/css%E7%9B%92%E6%A8%A1%E5%9E%8B/">
                        <span class="hidden-mobile">css盒模型</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "浏览器渲染以及性能优化&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>




















</body>
</html>
